import {Card, Col, Row, Tabs} from 'antd';
import HttpRequest from '@/utils/HttpRequest';
import {defaultDomain} from '@/config/domain';


import {FormatDate, FormatTime} from '@/utils/DateTime'
import {Area} from '@ant-design/charts'
import React, {useEffect, useState} from 'react'

const {TabPane} = Tabs

const DashBoard: React.FC = () => {
  const [data, setData] = useState([])
  const [statData, setStatData] = useState([])
  const [tpsData, setTpsData] = useState([])
  useEffect(() => {
    asyncFetch()
  }, [])

  const asyncFetch = async () => {
    ///dashboard/topicCurrent?_=1647847365720
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: '/dashboard/topicCurrent?' + Math.random(),
      method: 'GET',
      params: {},
    })

    if (res.status == 0) {
      // @ts-ignore
      const data = res.data

      console.log('data', data)
      let dataList = []
      for (let i in data) {
        let item = data[i]
        let itemList = item.split(',')
        let v = Number.parseInt(itemList[1])
        if (v > 0) {
          dataList.push({
            value: Number.parseInt(itemList[1]),
            //topic: i+20,
            topic: itemList[0],
            category: 'topic',
          })
        }
      }
      //console.log('data>>', dataList)
      // @ts-ignore
      setData(dataList)
    }

    stats()
    tpsStats()
  }

  async function tpsStats() {
    let today = FormatDate(new Date().getTime() / 1000)
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url:
        '/dashboard/broker.query?date=' +
        today +
        '&_=' +
        Math.random().toString(),
      method: 'GET',
      params: [],
    })
    console.log('res=', res)
    // @ts-ignore
    const data = res.data
    let tpsList = []
    if (data) {
      for (let s in data) {
        let item = data[s]
        for (let d in item) {
          let vs = item[d].split(',')
          tpsList.push({
            value: Number.parseFloat(vs[1]),
            time: Number.parseInt(vs[0]),
            topic: FormatTime(Number.parseInt(vs[0]) / 1000),
            category: s,
          })
        }
      }
    }
    console.log('tpsList >>>', tpsList)
    // @ts-ignore
    setTpsData(tpsList)
  }

  async function stats() {
    const res = await HttpRequest({
      baseURL: defaultDomain,
      url: '/cluster/list.query',
      method: 'GET',
      params: [],
    })
    // console.log('res=', res)
    // @ts-ignore
    const data = res.data
    let brokerList = []
    let commitLogList = []
    let scheLogList = []
    if (data && data.brokerServer) {
      let brokerServer = data.brokerServer
      if (brokerServer) {
        for (let i in brokerServer) {
          let serverList = brokerServer[i]
          for (let s in serverList) {
            let instance = serverList[s]
            let bro = {}
            bro['broker'] = i
            // @ts-ignore
            bro['yesterdayPut'] =
              instance.msgPutTotalTodayMorning -
              instance.msgPutTotalYesterdayMorning
            bro['yesterdayGet'] =
              instance.msgGetTotalTodayMorning -
              instance.msgGetTotalYesterdayMorning

            bro['todayPut'] =
              instance.msgPutTotalTodayNow - instance.msgPutTotalTodayMorning
            bro['todayGet'] =
              instance.msgGetTotalTodayNow - instance.msgGetTotalTodayMorning

            brokerList.push({
              value: Number.parseInt(bro['yesterdayPut']),
              topic: '昨日生产总数',
              category: bro['broker'],
            })

            brokerList.push({
              value: Number.parseInt(bro['yesterdayGet']),
              topic: '昨日消费总数',
              category: bro['broker'],
            })

            brokerList.push({
              value: Number.parseInt(bro['todayPut']),
              topic: '今天生产总数',
              category: bro['broker'],
            })

            brokerList.push({
              value: Number.parseInt(bro['todayGet']),
              topic: '今天消费总数',
              category: bro['broker'],
            })

            //commitLogDiskRatio: "0.6436226278267216"
            // commitLogMaxOffset: "204449605040"
            // commitLogMinOffset: "204010946560"
            // consumeQueueDiskRatio: "0.6436226278267216"
            commitLogList.push({
              value: Number.parseFloat(instance['commitLogDiskRatio']),
              topic: 'commitLogDiskRatio',
              category: bro['broker'],
            })
            commitLogList.push({
              value: Number.parseFloat(instance['consumeQueueDiskRatio']),
              topic: 'consumeQueueDiskRatio',
              category: bro['broker'],
            })
            commitLogList.push({
              value: Number.parseFloat(instance['commitLogMinOffset']),
              topic: 'commitLogMinOffset',
              category: bro['broker'],
            })
            commitLogList.push({
              value: Number.parseFloat(instance['commitLogMaxOffset']),
              topic: 'commitLogMaxOffset',
              category: bro['broker'],
            })

            for (let q = 1; q <= 18; q++) {
              let name = 'scheduleMessageOffset_' + q
              let item = instance[name].split(',')

              scheLogList.push({
                value: Number.parseFloat(item[0]),
                category: 'startOffset',
                topic: name,
              })
              scheLogList.push({
                value: Number.parseFloat(item[1]),
                category: 'endOffset',
                topic: name,
              })
            }
          }
        }
      }
      // @ts-ignore
      setStatData(brokerList)

    }
  }

  const config: any = {
    data: data,
    xField: 'topic',
    yField: 'value',
    seriesField: 'category',
    yAxis: {
      type: 'log',
      range: [0, 1],
      tickCount: 24,
    },
    xAxis: {
      tickCount: 8,
    },
    legend: {
      position: 'top',
    },
    smooth: true,
    animation: {
      appear: {
        animation: 'wave-in',
        duration: 1000,
      },
    },
    areaStyle: () => {
      return {
        fill: 'l(20) 0:#ffffff 0.2:#7ecfff 0.5:#7ec2f3 1:#1890ff',
      }
    },
  }

  const t_config: any = {
    data: statData,
    xField: 'topic',
    yField: 'value',
    seriesField: 'category',
    yAxis: {
      type: 'log',
    },
    legend: {
      position: 'top',
    },
    smooth: true,
    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
    areaStyle: () => {
      return {
        fill: 'l(270) 0:#ffffff 0.2:#7ecfff 0.5:#7ec2f3 1:#1890ff',
      }
    },
  }


  const tpsConf: any = {
    data: tpsData,
    xField: 'topic',
    yField: 'value',
    seriesField: 'category',
    xAxis: {
      tickCount: 24,
      range: [0, 1],
    },
    smooth: true,
    legend: {
      position: 'top',
    },
    areaStyle: () => {
      return {
        fill: 'l(270) 0:#ffffff 0.2:#7ecfff 0.5:#7ec2f3 1:#1890ff',
      }
    },

    animation: {
      appear: {
        animation: 'path-in',
        duration: 1000,
      },
    },
  }

  return (
    <Card title={'消息分析'} style={{margin: '10px'}}>
      <Tabs defaultActiveKey="1">
        <TabPane tab="topic消息" key="1">
          <Row gutter={[6, 24]}>
            <Col span={24}>
              <Card>
                <Area
                  {...config}
                  xAxis={{
                    label: {
                      rotate: -50,
                      offset: 30,
                      autoEllipsis: true,
                      style: {
                        fontSize: 12,
                        textBaseline: 'bottom',
                      },
                    },
                  }}
                ></Area>
              </Card>
            </Col>
          </Row>
        </TabPane>

        <TabPane tab="Broker Tps" key="2">
          <Row>
            <Col span={24}>
              <Card>
                <Area
                  {...tpsConf}
                  xAxis={{
                    label: {
                      rotate: -50,
                      offset: 20,
                    },
                  }}
                />
              </Card>
            </Col>
          </Row>
        </TabPane>
        <TabPane tab="消息统计" key="3">
          <Row gutter={[6, 24]}>
            <Col span={24}>
              <Card>
                <Area {...t_config} />
              </Card>
            </Col>
          </Row>
        </TabPane>

      </Tabs>
    </Card>
  )
}


export default DashBoard
